use crate::dao::SettingsDao;
use r2d2::Pool;
use r2d2_sqlite::SqliteConnectionManager;

pub struct SettingsService {
    settings_dao: SettingsDao,
}

impl SettingsService {
    pub fn new(pool: Pool<SqliteConnectionManager>) -> Self {
        let settings_dao = SettingsDao::new(pool);
        SettingsService { settings_dao }
    }

    pub fn init_table(&self) -> Result<(), rusqlite::Error> {
        self.settings_dao.create_table()
    }

    pub fn set_setting(&self, key: &str, value: &str) -> Result<(), rusqlite::Error> {
        let keyis_exists = self.settings_dao.exists(key)?;
        if keyis_exists {
            self.settings_dao.update(key, value)
        } else {
            self.settings_dao.insert(key, value)
        }
    }

    pub fn get_setting(&self, key: &str) -> Result<Option<String>, rusqlite::Error> {
        let keyis_exists = self.settings_dao.exists(key)?;
        if keyis_exists {
            self.settings_dao.get(key)
        } else {
            Ok(None)
        }
    }
}
